<template>
  <div class="box">
    <div class="header-box" v-if="isMine || isAll">
      <div class="header">
        <a-row type="flex" align="middle" justify="center">
          <template v-for="(basic, basicIndex) in basicData" :key="basicIndex">
            <a-divider
                type="vertical"
                style="height: 20px; background-color: #7cb305"
                v-if="basicIndex > 0"
            />
            <a-col :flex="1" style="text-align: center" class="header-content">
              <div class="num-info">
                {{ basic.num }}
              </div>
              <div>
                {{ basic.title }}
                <text-tip
                    v-if="basic.tips"
                    :tips="basic.tips"
                ></text-tip>
              </div>
            </a-col>
          </template>
        </a-row>
      </div>
    </div>
    <div class="flex justify-between header-clue">
      <div class="flex-1">
            <a-form layout="vertical">
              <a-row :gutter="8" :wrap="true" type="flex">
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索联系人名称"
                        v-model:value="searchParams.name"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索联系人电话"
                        v-model:value="searchParams.tel"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-input
                        placeHolder="搜索公司名称"
                        v-model:value="searchParams.company"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        :allowClear="true"
                        placeholder="请选择意向项目"
                        v-model:value="searchParams.village_id"
                        :options="villageOptions"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" v-if="isMine || isAll">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        placeholder="请选择客户状态"
                        :allowClear="true"
                        v-model:value="searchParams.status"
                        :options="customerStatusOptions"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        style="width: 100%"
                        placeholder="请选择客户渠道"
                        :allowClear="true"
                        v-model:value="searchParams.channel_id"
                        :options="customerChannelOptions"
                    >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-select
                        ref="select"
                        v-model:value="searchParams.tag_id"
                        style="width: 100%"
                        placeholder="请选择标签"
                        :options="tagList"
                        :field-names="{ label: 'name', value: 'id', options: 'children' }"
                        mode="multiple"
                    ></a-select>
                  </a-form-item>
                </a-col>

                <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24">
                  <a-form-item>
                    <a-range-picker
                        class="w-100p"
                        v-model:value="searchParams.created_time"
                        :value-format="dateFormatStr"
                        @change="handleRangePickerChange"
                    />
                  </a-form-item>
                </a-col>

                <a-col>
                  <a-form-item label="">
                    <a-space>
                      <a-button @click="reset">重置</a-button>
                      <a-button type="primary" @click="getDataList(true)">
                        搜索
                      </a-button>
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
      </div>
    </div>
    <CustomTable
        ref="customTableRef"
        :columns="columns"
        :hasPagination="true"
        :requestInfo="{
          service: '/org', // 请求服务
          serviceUrl: '/business/customer/list', // 请求url
          serviceType: 'post', // 请求方式
        }"
        :extraParams="{
          ...searchParams
        }"
        :tableConfig="$store.getters.tableConfig"
        tableId="CustomerBrandList"
        @request="$utils.commonRequest"
        :rightButtons="rightButtons"
        :excludeImport="!isAll && !isMine"
        :customImport="handleMenuClick"
        @changeExportData="changeExportData"
        :excludeExport="!isAll && !isMine && !isOpenSea"
        @getListResult="getListResult"
        :row-selection="rowSelection"
        
      >
      <template #column-tag_arr="{text, record }">
        <tempalte v-if="text?.length">
            <a-tag v-for="(item, index) in text" :key="index">{{ item.name }}</a-tag>
          </tempalte>
          <tempalte v-else>
            <span>--</span>
          </tempalte>
          <a-button type="link" v-if="!isOpenSea" @click.stop="handleEditTag(record)"
                    style="margin-left: 4px">
            <FormOutlined/>
          </a-button>
      </template>
      <template #column-action="{ record }">
          <a-button type="link" v-if="isOpenSea && isAdmin" @click.stop="handleAllot(record)">
            指定分配
          </a-button>
          <a-popconfirm
              title="确定领取该客户？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleGet(record)"
              v-if="isOpenSea && record.is_receive && !isAdmin"
          >
            <a-button type="link">
              领取
            </a-button>
          </a-popconfirm>
          <a-button type="link" v-if="record.is_follow && !isOpenSea && !isApproval"
                    :disabled="record.status == 30" @click.stop="handleFollow(record)">
            跟进
          </a-button>
          <a-button type="link" v-if="isAll && canRecycle" @click.stop="handleRecycle(record)">
            回收
          </a-button>
          <a-button type="link" @click.stop="handleDetail(record)"
                    v-if="!isApproval">
            详情
          </a-button>
          <a-button type="link" @click.stop="toApprovalDetail(record)"
                    v-if="isApproval">
            审批详情
          </a-button>

        </template>
      </CustomTable>

    <!-- 客户跟进 -->
    <FollowUpCustomer
        :visible="followVisible"
        :id="detailId"
        @handleCancel="handleFollowClose"
        @success="handleFollowSuccess"
    />

    <!-- 新增客户 -->
    <AddCustomer
        :visible="addCustomerVisible"
        :isAdmin="isAdmin"
        @cancelAdd="handleAddCancel"
        @success="addSuccess"
    />

    <!--  客户详情  -->
    <CustomerDetail
        :visible="detailVisible"
        :id="detailId"
        @handleCancel="handleDetailClose"
    />

    <!--  编辑标签  -->
    <SelectTagModal
        :visible="editTagVisible"
        :tags="currentTags"
        :id="detailId"
        :isSave="true"
        @handleCancel="selectTagCancel"
        @success="selectTagSuccess"
    />


    <!-- 指定分配 -->
    <AllotUserModal
        :visible="allotVisible"
        :ids="allotIds"
        :userList="userList"
        @success="successAllot"
        @handleCancel="closeAllot"
    />

    <!-- 审批详情-->
    <ApprovalDetail
        :title="'客户审批详情'"
        :origin="originFlag"
        :visible="approvalVisible"
        :id="approvalId"
        @closeDrawer="() => (approvalVisible = false)"
        @statusChange="handleStatusChange"
    />

  </div>
</template>

<script>
import {reactive, ref, toRefs, computed, watch, defineComponent, createVNode} from "vue";
import request from "../../../../common/utils/request";
import {useRoute, useRouter} from "vue-router";
import {TextTip} from "bl-common-vue3";
import store from "@/store/index";
import {Form, message, Modal} from "ant-design-vue";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
import AddCustomer from "@/views/village/BusinessManage/modules/AddCustomer.vue";
import CustomerDetail from "@/views/village/BusinessManage/modules/CustomerDetail.vue";
import FollowUpCustomer from "@/views/village/BusinessManage/modules/FollowUpCustomer.vue";
import SelectTagModal from "@/views/village/BusinessManage/tagModules/SelectTagModal.vue";
import AllotUserModal from "@/views/village/BusinessManage/modules/AllotUserModal.vue";
import ApprovalDetail from "./ApprovalDetail.vue"
import {
  ExclamationCircleOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  FormOutlined
} from "@ant-design/icons-vue";
import _ from "lodash";
import { CustomTable } from "bl-common-vue3";

export default defineComponent({
  name: "IntendedCustomerList",
  props: {
    activeKey: {
      type: [Number, String],
      default: '',
    },
    sourceType: {
      type: String,
      default: '',
    },
    villageOptions: {
      type: Array,
      default: () => [],
    },
    customerChannelOptions: {
      type: Array,
      default: () => [],
    },
    isAdmin: {
      type: Boolean,
      default: false,
    },
    canRecycle: {
      type: Boolean,
      default: false,
    }
  },
  components: {
    ApprovalDetail,
    EyeOutlined, EyeInvisibleOutlined,
    FormOutlined,
    SelectTagModal,
    TextTip,
    AddCustomer,
    CustomerDetail,
    FollowUpCustomer,
    AllotUserModal,
    CustomTable
  },
  setup(props, {emit}) {
    const COLUMNS = [
      {
        title: "联系人",
        align: "center",
        dataIndex: "name",
        key: "name",
        fixed: store.getters.isMobile ? undefined : "left",
        width: 150,
      },
  
    
      {
        title: "联系电话",
        align: "center",
        dataIndex: "tel",
        key: "tel",
        width: 150,
      },
      {
        title: "公司名称",
        align: "center",
        dataIndex: "company",
        key: "company",
        customRender: ({text}) => {
          return text || '--';
        },
        width: 150,
      },
      {
        title: "品牌名称",
        align: "center",
        dataIndex: "brand.brand_name",
        key: "brand.brand_name",
        width: 100,
      },
    
      {
        title: "成交率",
        align: "center",
        dataIndex: "deal_precent",
        key: "deal_precent",
        customRender: ({text}) => {
          return text + '%';
        },
        width: 100,
      },
      {
        title: "行业",
        align: "center",
        dataIndex: "industry",
        key: "industry",
        customRender: ({text, record}) => {
          return record?.org_industry?.name || '--';
        },
        width: 120,
      },
      {
        title: "客户状态",
        align: "center",
        dataIndex: "status_txt",
        key: "status_txt",
        width: 150,
      },
      {
        title: "客户类型",
        align: "center",
        dataIndex: "type",
        key: "type",
        columnType: "dictionary",
        dictType: "org_custom_type",
        width: 100,
      },
      {
        title: "更新时间",
        align: "center",
        dataIndex: "updated_at",
        key: "updated_at",
        width: 180,
      },
      {
        title: "关联渠道",
        align: "center",
        dataIndex: "channel_name",
        key: "channel_name",
        customRender: ({text}) => {
          return text || '--';
        },
        width: 150,
      },
      {
        title: "客户预算",
        align: "center",
        dataIndex: "budget_amount",
        key: "budget_amount",
        customRender: ({text}) => {
          return text || text == 0 ? text + '元' : '--';
        },
        width: 150,
      },
      {
        title: "意向项目",
        align: "center",
        dataIndex: "village_name",
        key: "village_name",
        width: 150,
      },
      {
        title: "需求面积段",
        align: "center",
        dataIndex: "expect_area_max",
        key: "expect_area_max",
        customRender: ({text, record}) => {
          return `${record?.expect_area_min || ''}-${record?.expect_area_max || ''}m²`
        },
        width: 150,
      },
      {
        title: "预计签约时间",
        align: "center",
        dataIndex: "expect_contract",
        key: "expect_contract",
        customRender: ({text}) => {
          return text || '--';
        },
        width: 180,
      },
      {
        title: "标签",
        align: "center",
        dataIndex: "tag_arr",
        key: "tag_arr",
        width: 180,
      },
      {
        title: "操作",
        align: "center",
        dataIndex: "action",
        key: "action",
        width: 180,
        fixed: "right",
      },
    ]

    // tab表格实例
    const customTableRef = ref(null);

    const $router = useRouter();
    const state = reactive({
      dataList: [],
      basicData: [
        {
          title: '总客户数量',
          num: 0,
        },
        {
          title: '本日新增数量',
          num: 0,
        },
        {
          title: '本周新增数量',
          num: 0,
        },
        {
          title: '本月新增数量',
          num: 0,
        },
      ],
      columns: COLUMNS,
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      addCustomerVisible: false,
      detailId: 0,
      detailVisible: false,
      followVisible: false,
      editTagVisible: false,
      currentTags: [],
      customerStatusOptions: [],
      selectedRowKeys: [],
      allotVisible: false,
      allotIds: [],
      userList: [],
      approvalVisible: false,
      approvalId: 0,
      originFlag: false,
      tagList: [],

      rightButtons:[
        {
          name: "+新增客户",
          key: "addCustomer",
          onClick: () => {
            addCustomer();
          },
          show: props.sourceType === 'all' || props.sourceType === 'mine',
          props: {
            type: "primary",
          },
        },
        {
          name: "批量指定分配",
          key: "allot",
          onClick: () => {
            handleAllot();
          },
          show: props.sourceType === 'openSea' && props.isAdmin,
          props: {
            ghost: true,
            type: "primary",
          },
        },
      ]
    });


    const searchParams = reactive({
      name: "", // 联系人名称
      tel: "", // 联系人电话
      company: '', // 公司名称
      village_id: undefined, // 意向项目id
      status: undefined, // 客户状态
      channel_id: undefined, // 客户渠道id
      tag_id: undefined, // 标签id
      created_time: undefined,
      created_start: undefined,
      created_end: undefined,
    });

    const isMine = computed(() => props.sourceType === 'mine'); // 我的客户
    const isAll = computed(() => props.sourceType === 'all'); // 全部客户
    const isOpenSea = computed(() => props.sourceType === 'openSea'); // 客户公海
    const isApproval = computed(() => props.sourceType === 'approvalIng'); // 审批中


    const onSelectedRowChange = (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
    };

    const rowSelection = computed(() =>
        // props.isAdmin && isOpenSea.value
        props.isAdmin
            ? {
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectedRowChange,
            }
            : null
    );

    const {resetFields} = useForm(searchParams, {});

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const getListResult= (resultData)=>{
        state.basicData[0].num = resultData?.total || 0;
        state.basicData[1].num = resultData?.dayCount || 0;
        state.basicData[2].num = resultData?.weekCount || 0;
        state.basicData[3].num = resultData?.monthCount || 0;
    }

    const getDataList = (init = false) => {
   
      const params = {
        page: state.page,
        limit: state.limit,
      };
      if (searchParams.created_time) {
        searchParams.created_start = searchParams.created_time[0];
        searchParams.created_end = searchParams.created_time[1];
      }
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      delete params.created_time;
      if (isMine.value) {
        params.is_all = 0;
      }
      if (isAll.value) {
        params.is_all = 1;
      }

      if (props.sourceType == 'mine') {
        params.type = "my"
      } else if (props.sourceType == 'all') {
        params.type = "all"
      } else if (props.sourceType == 'openSea') {
        params.type = "pool"
      } else if (props.sourceType == 'approvalIng') {
        params.type = "approvalIng";
      }
      searchParams.type = params.type
      if (init) {
        state.selectedRowKeys = [];
      }
      if(customTableRef.value){
          customTableRef.value.loadData(true);
        }
    };

    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };

    const reset = () => {
      resetFields();
      getDataList(true)
    };

    const handleRangePickerChange = (date, dateString) => {
      searchParams.created_time = date;
    };

    // 新增客户
    const addCustomer = () => {
      state.addCustomerVisible = true;
    };

    const handleAddCancel = () => {
      state.addCustomerVisible = false;
    };
    const addSuccess = () => {
      handleAddCancel();
      getDataList();
    };

    const getStatus = () => {
      request.get("/org", "/business/customer/statusList", {}).then((res) => {
        state.customerStatusOptions = res.list.map((item) => ({
          value: item.status,
          label: item.name,
          ...item,
        }));
      });
    };

    const getTeemUserList = () => {
      request
          .get("/org", "/business/customerTeam/teamUserIndex")
          .then((res) => {
            state.userList = res?.data?.map((item) => {
              return {
                label: item.name,
                value: item.uid,
              };
            });
          });
    };
    const getTagList = () => {
      request
          .get("/org", "/business/customerTag/index", {})
          .then((res) => {
            state.tagList = res?.list || [];
          })
    };
    const init = () => {
      let columns = _.cloneDeep(COLUMNS);
      if (props.activeKey == 4 && props.sourceType == 'openSea') {
        let _columns = [];
        columns.forEach((v) => {
          if (v.key == 'tag_arr') {
            v = {
              title: "备注",
              align: "center",
              dataIndex: "remark",
              key: "remark",
              width: 180,
              customRender: ({text}) => {
                return text || '--';
              },
            };
          }
          if (v.key !== 'status_txt') {
            _columns.push(v)
          }
        })
        columns = _columns;
        getTeemUserList();
      }
      state.columns = columns;
      getTagList();
      getStatus();
      getDataList(true)
    };

    // 查看详情
    const handleDetail = (record) => {
      state.detailId = record.id;
      state.detailVisible = true;
    };

    const handleDetailClose = () => {
      state.detailId = 0;
      state.detailVisible = false;
    };

    const handleFollowClose = () => {
      state.detailId = 0;
      state.followVisible = false;
      state.selectedRowKeys = [];
    };

    const handleFollowSuccess = () => {
      handleFollowClose();
      getDataList();
    };

    const handleFollow = (record) => {
      state.detailId = record.id;
      state.followVisible = true;
    };

    const handleMenuClick = () => {
      $router.push({name: "importCustomer"});
    };

    const selectTagCancel = () => {
      state.detailId = 0;
      state.currentTags = [];
      state.editTagVisible = false;
    };

    const selectTagSuccess = () => {
      selectTagCancel();
      getDataList();
    };

    const handleEditTag = (record) => {
      state.detailId = record.id;
      state.currentTags = record?.tag_arr || [];
      state.editTagVisible = true;
    };

    const handleRecycle = (record) => {
      Modal.confirm({
        title: () => "提示",
        content: () => "确定要回收该客户吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        okText: () => "确定",
        onOk() {
          request
              .get("/org", "/business/customer/recovery", {id: record.id})
              .then((res) => {
                message.success(res?.msg || '操作成功');
                state.selectedRowKeys = [];
                getDataList();
              })
        },
      });
    };

    const handleAllot = (record) => {
      if (record) {
        // 单个领取
        state.allotIds = [record.id];
        state.allotVisible = true;
      } else {
        // 批量领取
        if (!state.selectedRowKeys?.length) {
          message.warning("请先选择需要分配的客户");
          return;
        }
        state.allotIds = _.cloneDeep(state.selectedRowKeys);
        state.allotVisible = true;
      }
    };

    // 招商专员-领取客户
    const handleGet = (record) => {
      request
          .get("/org", "/business/customer/receive", {id: record.id})
          .then((res) => {
            message.success(res?.msg || '领取成功');
            getDataList();
          })
   
    };

    const closeAllot = () => {
      state.allotIds = [];
      state.allotVisible = false;
    };

    const successAllot = () => {
      state.selectedRowKeys = [];
      closeAllot();
      getDataList();
    };

    watch(
        () => props.activeKey,
        (val) => {
          if (val) {
            if ((val == 1 && props.sourceType == 'mine') || (val == 2 && props.sourceType == 'all') || (val == 4 && props.sourceType == 'openSea') || (val == 5 && props.sourceType == 'approvalIng')) {
              init();
            }
          }
        },
        {immediate: true}
    );



    const changeExportData=(list)=>{
      list.forEach((item)=>{
        item.tag_arr = item?.tag_arr?.map((tag)=>tag.name).join(',')
      })
      customTableRef.value.setExportData(list)
    }

    const toApprovalDetail = (value) => {
      console.log(value)
      state.originFlag = (value.origin == 2) ? true : false;
      state.approvalId = value.approval_id;
      state.approvalVisible = true;
    }
    const handleStatusChange = () => {
      state.approvalVisible = false;
      setTimeout(() => {
        getDataList(true);
      }, 1000)
    }

    return {
      ...toRefs(state),
      pagination,
      searchParams,
      dateFormatStr,
      isMine,
      isAll,
      isOpenSea,
      rowSelection,
      handleTableChange,
      handleRangePickerChange,
      reset,
      getDataList,
      addCustomer,
      addSuccess,
      handleMenuClick,
      handleDetail,
      handleAddCancel,
      handleDetailClose,
      handleFollow,
      handleEditTag,
      selectTagCancel,
      selectTagSuccess,
      handleFollowClose,
      handleFollowSuccess,
      handleRecycle,
      handleAllot,
      closeAllot,
      successAllot,
      handleGet,
      isApproval,
      toApprovalDetail,
      handleStatusChange,
      getListResult,

      customTableRef,
      changeExportData

    };
  },
});

</script>

<style lang="less" scoped>
.box {
  padding: 10px;

  .header-clue {
    padding: 0 14px;
  }

  .header-box {
    background: #fff;
    padding: 4px 10px 14px 10px;
  }

  .header {
    background-color: rgb(240, 242, 245);
    padding: 16px 10px;

    .num-info {
      color: @primary-color;
      font-size: 30px;
      max-width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;
    }
  }

  .header-content {
    width: 0;
  }
}

:deep(.ant-tabs-content) {
  height: 100%;
}

.ant-tag {
  margin: 4px 8px 4px 0;
}

:deep(.ant-table-title) {
  padding: 0;
}
</style>
